package top.yaofengqiao.springcloudsimple.auth.biz.domain.security.model;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yfq
 * @date 2024/5/31 15:28
 * @description
 */
@Data
@Builder
@AllArgsConstructor
public class ClientInfo implements ClientDetails {
    private final Client client;

    @Override
    public String getClientId() {
        return client.getClientId();
    }

    @Override
    public Set<String> getResourceIds() {
        String resourceIds = client.getResourceIds();
        if (StrUtil.isEmpty(resourceIds)) return Collections.emptySet();

        String[] arr = resourceIds.split(",");
        return Arrays.stream(arr).collect(Collectors.toSet());
    }

    @Override
    public boolean isSecretRequired() {
        return client.getSecretRequire();
    }

    @Override
    public String getClientSecret() {
        return client.getClientSecret();
    }

    @Override
    public boolean isScoped() {
        return client.getScopeRequire();
    }

    @Override
    public Set<String> getScope() {
        String scope = client.getScope();
        if (StrUtil.isEmpty(scope)) return Collections.emptySet();

        String[] arr = scope.split(",");
        return Arrays.stream(arr).collect(Collectors.toSet());
    }

    @Override
    public Set<String> getAuthorizedGrantTypes() {
        String authorizedGrantTypes = client.getAuthorizedGrantTypes();
        if (StrUtil.isEmpty(authorizedGrantTypes)) return Collections.emptySet();

        String[] arr = authorizedGrantTypes.split(",");
        return Arrays.stream(arr).collect(Collectors.toSet());
    }

    @Override
    public Set<String> getRegisteredRedirectUri() {
        return null;
    }

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
        String authorities = client.getAuthorities();
        if (StrUtil.isEmpty(authorities)) return Collections.emptySet();

        String[] arr = authorities.split(",");
        return Arrays.stream(arr).map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
    }

    @Override
    public Integer getAccessTokenValiditySeconds() {
        return client.getAccessTokenValidity();
    }

    @Override
    public Integer getRefreshTokenValiditySeconds() {
        return client.getRefreshTokenValidity();
    }

    @Override
    public boolean isAutoApprove(String scope) {
        return true;
    }

    @Override
    public Map<String, Object> getAdditionalInformation() {
        return null;
    }
}
